package com.kayeah82.application.avatar.qq.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.PostConstruct;

/**
 * @author kayeah82
 * */
@Configuration
class ThymeleafConfig {

    private static final String URL_PATH_SEPERATOR = "/";

    private SpringTemplateEngine templateEngine;
    private ThymeleafViewResolver viewResolver;

    @Value("${spring.thymeleaf.cache}")
    private boolean enableCache;

    /**
     * @param templateEngine 采用spring boot默认
     */
    @Autowired
    public void setTemplateEngine(SpringTemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    /**
     * @param viewResolver 采用spring boot默认
     */
    @Autowired
    public void setViewResolver(ThymeleafViewResolver viewResolver) {
        this.viewResolver = viewResolver;
    }

    @PostConstruct
    private void init() {
        templateEngine.addDialect(new Java8TimeDialect());
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setCache(enableCache);
        this.configureThymeleaf(viewResolver);
    }

    private void configureThymeleaf(ThymeleafViewResolver viewResolver) {
        if (!context.endsWith(URL_PATH_SEPERATOR)) {
            context += URL_PATH_SEPERATOR;
        }
        viewResolver.addStaticVariable("context", context);
        viewResolver.addStaticVariable("assetsContext", assetsContext);
    }

    @Value("${context}")
    private String context;

    @Value("${assets.context}")
    private String assetsContext;
}

